package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.entity.supplier.RecommendReason;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.dto.SupplierProjectAcceptDTO;
import com.qili.service.SysUserService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supplier.RecommendReasonService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.util.DateUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangxiaopeng
 * @date 2021/4/8
 * @description 综合对比  项目招标时间截止计算生成应接人对应信息和分数
 */
@Log
public class RecommendReasonJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private ProjectNoticeServie projectNoticeServie;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    private RecommendReasonService recommendReasonService;
    @Autowired
    private SupplierProjectAcceptService spaService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("RecommendReasonJob：启动任务=======================");

        log.info("RecommendReasonJob=======开始==================================");
        String lockkey = "RecommendReasonJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            run();
        } catch (Exception e) {
            log.info("RecommendReasonJob=======出现异常了==================================");
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            log.info("RecommendReasonJob=======释放锁==================================");
            unlock(lockkey, uuId);
        }
        System.out.println("RecommendReasonJob：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {
        try {
            // 供需  ----综合对比  项目招标时间截止计算生成应接人对应信息和分数
            Date currdate = new Date();
            //查询项目表
            List<SupplierProject> list = supplierProjectManagerService.selectAll();
            SupplierProjectAccept spa = new SupplierProjectAccept();
            SupplierProjectAcceptDTO spaDTO = new SupplierProjectAcceptDTO();
            RecommendReason reason = new RecommendReason();
            if (list != null && list.size() > 0) {
                for (SupplierProject project : list) {
                    reason.setProjectId(project.getSupProjectId());
                    //判断该项目是否已生成
                    List<RecommendReason> reasonList = recommendReasonService.select(reason);
                    if (reasonList == null || reasonList.size() == 0) {
                        Date zbEndDate = DateUtil.parseDate(project.getZbEndDate(), "yyyy-MM-dd HH:mm");
                        if (currdate.after(zbEndDate)) {
                            spa.setSupProjectId(project.getSupProjectId());
                            //根据项目查询应接人的数据
                            List<SupplierProjectAccept> list1 = spaService.select(spa);
                            if (list1 != null && list1.size() > 0) {
                                for (SupplierProjectAccept supa : list1) {
                                    recommendReasonService.insertReason(supa);
                                }
                            }
                            spaDTO.setSupProjectId(project.getSupProjectId());
                            spaDTO.setScoreDesc("111");
                            //根据应接人的总分数来进行排序
                            updateAccept(spaDTO);
                            //平台推荐顺序
                            updateReason(project.getSupProjectId());
                        }
                    }
                }
            }
            System.out.println("JobDemo1：执行完毕=======================");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //根据应接人的总分数来进行排序
    public void updateAccept(SupplierProjectAcceptDTO spaDTO) {
        List<SupplierProjectAcceptDTO> list = spaService.selectListByScore(spaDTO);
        if (list != null && list.size() > 3) {
            int a = 1;
            for (int i = 0; i < 3; i++) {
                list.get(i).setAcceptOrder(a + "");
                a++;
                spaService.updateByPrimaryKeySelective(list.get(i));
            }
        } else {
            int a = 1;
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setAcceptOrder(a + "");
                a++;
                spaService.updateByPrimaryKeySelective(list.get(i));
            }
        }
    }

    //平台推荐顺序
    public void updateReason(String id) {
        Map map = new HashMap<>();
        map.put("projectId", id);
        map.put("scoreDesc", "123");
        List<RecommendReason> list = recommendReasonService.selectReason(map);
        if (list != null && list.size() > 0) {
            int a = 1;
            for (RecommendReason re : list) {
                re.setRecommendOrder(a + "");
                a++;
                recommendReasonService.updateByPrimaryKeySelective(re);
            }
        }
    }


    public void lock(String key, String uuId) {
        for (; ; ) {
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }
}
